import { login, logout, getInfo, loginBySms } from '@/api/user'

const state = {
  token: localStorage.getItem('token'),
  name: '',
  avatar: '',
  roles: [],
  userId: null,
  userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  }
}

const actions = {
  // 用户登录
  login({ commit, dispatch }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          localStorage.setItem('token', data.token)
          
          // 登录成功后立即获取用户信息
          dispatch('getInfo')
            .then(() => {
              resolve()
            })
            .catch(error => {
              reject(error)
            })
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 短信验证码登录
  loginBySms({ commit, dispatch }, smsInfo) {
    const { phone, code } = smsInfo
    return new Promise((resolve, reject) => {
      loginBySms({ phone: phone.trim(), code: code.trim() })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          localStorage.setItem('token', data.token)
          
          // 登录成功后立即获取用户信息
          dispatch('getInfo')
            .then(() => {
              resolve()
            })
            .catch(error => {
              reject(error)
            })
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          const { data } = response
          if (!data) {
            reject('验证失败，请重新登录')
          }

          const { roles, name, avatar, id } = data
          
          // 保存完整的用户信息
          commit('SET_USER_INFO', data)
          commit('SET_ROLES', roles || [])
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar || '')
          commit('SET_USER_ID', id)
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 用户登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_USER_INFO', {})
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 移除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_USER_INFO', {})
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 